#include "decoder/common/subtitle_sync_manager.hpp"

namespace WD {

SubtitleSyncManager& SubtitleSyncManager::instance() {
    static SubtitleSyncManager inst;
    return inst;
}

void SubtitleSyncManager::insert(int64_t pts, double timestamp) {
    std::lock_guard<std::mutex> lock(mtx_);

    timestamp_map_[pts] = timestamp;
    pts_queue_.push_back(pts);

    if (pts_queue_.size() > max_entries_) {
        int64_t oldest = pts_queue_.front();
        pts_queue_.pop_front();
        timestamp_map_.erase(oldest);
    }
}

std::optional<double> SubtitleSyncManager::query(int64_t pts) {
    std::lock_guard<std::mutex> lock(mtx_);
    auto it = timestamp_map_.find(pts);
    if (it != timestamp_map_.end()) {
        return it->second;
    }
    return std::nullopt;
}

void SubtitleSyncManager::clear() {
    std::lock_guard<std::mutex> lock(mtx_);
    timestamp_map_.clear();
    pts_queue_.clear();
}

void SubtitleSyncManager::setMaxEntries(size_t max_entries) {
    std::lock_guard<std::mutex> lock(mtx_);
    max_entries_ = max_entries;
}

}  // namespace WD
